package com.component;

import com.Demo.MainInterface;
import com.bean.Farmer;
import com.bean.Users;
import com.dao.UserDao;
import com.dao.FarmerDao;
import com.util.ScreenUtils;
import com.util.SelectUsers;
import com.util.GetImage;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FarmingSystemGUI extends JFrame {
    private JButton loginButton;//登录按钮
    private JButton registerButton;//注册按钮
    private JTextField usernameField;//用户名文本框
    private JPasswordField passwordField;//密码文本框
    private JComboBox<String> userTypeComboBox;//用户类型

    final int WIDTH = 600;
    final int HEIGHT = 400;
    //用于演示目的的内存用户数据库
   private Map<String, String> userDatabase;

    // 构造方法，初始化用户界面
    public FarmingSystemGUI() {
        initializeUI();
        userDatabase = new HashMap<>(); //key --- 表示用户名，不能重复  value --- 表示用户密码
//        userDatabase.put("adminName", "adminPassword"); //管理员用户
//        userDatabase.put("consumerName", "consumerPassword"); //消费者用户
//        userDatabase.put("farmerName", "farmerPassword"); // 农户
        List<Users> list = new SelectUsers().getUserData();
        for(Users u:list)
        {
            userDatabase.put(u.getUserName(),u.getPassword());
        }
    }

    // 初始化用户界面
    private void initializeUI() {
        setTitle("扶贫农产品销售系统");
        setBounds((ScreenUtils.getScreenWidth() - WIDTH) / 2, (ScreenUtils.getScreenHeight() - HEIGHT) / 2, WIDTH, HEIGHT);
        setLocationRelativeTo(null); // 将窗口置于屏幕上的中心
        this.setResizable(false);
        setIconImage(new GetImage().getImage("logo.png"));
        //setBounds(500,500,400, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//        URL url = FarmingSystemGUI.class.getResource("FarmingSystemGUI.jpg");
//        ImageIcon imageIcon = new ImageIcon(url);
//        Image img = imageIcon.getImage();
        Image img = new GetImage().getImage("FarmingSystemGUI.jpg");
        BackGroundPanel panel = new BackGroundPanel(img);
        panel.setBounds(0,0,WIDTH,HEIGHT);

        //JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(6, 2, 10, 10));

        JLabel userLabel = new JLabel("用户名:");
        userLabel.setHorizontalAlignment(JLabel.CENTER); //居中
        usernameField = new JTextField();
        usernameField.setHorizontalAlignment(JTextField.CENTER);// 用户名居中对齐
        JLabel passwordLabel = new JLabel("密码:");
        passwordLabel.setHorizontalAlignment(JLabel.CENTER);
        passwordField = new JPasswordField();
        passwordField.setHorizontalAlignment(JPasswordField.CENTER);
        JLabel userTypeLabel = new JLabel("用户类型:");
        userTypeLabel.setHorizontalAlignment(JLabel.CENTER);
        String[] userTypes = {"消费者", "农户", "管理员"};
        //userTypeComboBox = new JComboBox<>(new String[]{"消费者", "农户", "管理员"});
        userTypeComboBox = new JComboBox<>(userTypes);
        userTypeComboBox.setAlignmentX(Component.CENTER_ALIGNMENT);

        loginButton = new JButton("登录");
        loginButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                loginButtonClicked();
            }
        });

        registerButton = new JButton("注册");
        registerButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                registerButtonClicked();
            }
        });


        // // 设置按钮的字体和大小
        /*Font buttonFont = new Font("Arial", Font.PLAIN, 14);
        loginButton.setFont(buttonFont);
        registerButton.setFont(buttonFont);*/

        panel.add(userLabel);
        panel.add(usernameField);
        panel.add(passwordLabel);
        panel.add(passwordField);
        panel.add(userTypeLabel);
        panel.add(userTypeComboBox);
        panel.add(new JLabel()); // 空标签表示间距
        panel.add(loginButton);
        panel.add(new JLabel()); // 空标签表示间距
        panel.add(registerButton);

        // 设置边框以获得更好的美感
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        add(panel);
        //pack();
        setVisible(true);
    }

    // 处理登录按钮点击事件
    private void loginButtonClicked() {
        String username = usernameField.getText();
        String password = String.valueOf(passwordField.getPassword());
        String userType = (String) userTypeComboBox.getSelectedItem();

        if(username.length()==0||password.length()==0)
        {
            JOptionPane.showMessageDialog(this, "登录失败，请输入用户名或密码！");
        }
        else
        {
            if (authenticateUser(username, password, userType)) {
                openUserInterface(userType,username);
            } else {
                JOptionPane.showMessageDialog(this, "登录失败，用户名或密码或用户类型错误！");
            }
        }

    }

    // 注册用户按钮点击事件
    private void registerButtonClicked() {
        String username = usernameField.getText();
        String password = String.valueOf(passwordField.getPassword());
        String userType = (String) userTypeComboBox.getSelectedItem();

        if(username.length()==0||password.length()==0)
        {
            JOptionPane.showMessageDialog(this, "注册失败，请输入用户名或密码！");
        }
        else if(!username.matches("\\w+"))
        {
            JOptionPane.showMessageDialog(this, "注册失败，用户名只能包含英文数字下划线!");
        }
        else if(password.length()<=8)
        {
            JOptionPane.showMessageDialog(this, "注册失败，用户密码需要8位以上!");
        }
        else
        {
            if (userDatabase.containsKey(username)) {
                JOptionPane.showMessageDialog(this, "注册失败，用户名已存在!");
            } else {
                // 提示用户完善个人信息，并打开注册窗口
                JOptionPane.showMessageDialog(this, "请完善个人信息！");
                // 打开注册窗口
                openRegistrationWindow(username, password, userType);
            }
        }

    }

    // 打开注册窗口
    public void openRegistrationWindow(String username, String password, String userType) {
        JFrame registrationFrame = new JFrame("用户注册");
        //registrationFrame.setIconImage(new GetImage().getImage("logo.png"));
        //JDialog registrationDialog = new JDialog(this,"用户注册");

        registrationFrame.setSize(500, 650);
        registrationFrame.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        registrationFrame.setLocationRelativeTo(null);
        registrationFrame.setResizable(false);

//        URL url1 = MainInterface.class.getResource("Register.jpg");
//        ImageIcon imageIcon1 = new ImageIcon(url1);
//        Image img1 = imageIcon1.getImage();
//        BackGroundPanel registrationPanel = new BackGroundPanel(img1);

        BackGroundPanel registrationPanel = new BackGroundPanel(new GetImage().getImage("Register.jpg"));
        registrationPanel.setBounds(0,0,WIDTH,HEIGHT);
        //JPanel registrationPanel = new JPanel();
        registrationPanel.setLayout(new GridLayout(10, 2, 10, 10));

//        JLabel userLabel = new JLabel("用户名:");
//        JTextField regUsernameField = new JTextField();
//        regUsernameField.setText(username);
//
//        JLabel passwordLabel = new JLabel("密码:");
//        JPasswordField regPasswordField = new JPasswordField();
//        regPasswordField.setText(password);
//
//        JLabel userTypeLabel = new JLabel("用户类型:");
//        JTextField regUserTypeField = new JTextField();
//        regUserTypeField.setText(userType);

        JLabel userReallyNameLabel = new JLabel("真实姓名:");
        JTextField regUserReallyNameField = new JTextField();

        JLabel userGenderLabel = new JLabel("性别");
        JComboBox<String> regUserGenderBox = new JComboBox<>();
        regUserGenderBox.addItem("男");
        regUserGenderBox.addItem("女");

        JLabel userPNumLabel = new JLabel("联系电话:");
        JTextField regUserPNumField = new JTextField();

        JLabel userEmailLabel = new JLabel("电子邮箱:");
        JTextField regUserEmailField = new JTextField();

        JLabel userAddressLabel = new JLabel("家庭住址:");
        JTextField regUserAddressField = new JTextField();

        JButton completeRegistrationButton = new JButton("完成注册");
        //完成注册监测
        completeRegistrationButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 在此处添加注册逻辑，将用户信息保存到数据库或进行其他操作
                JPanel registrationErrorPanel = new JPanel();

                String userReallyName = regUserReallyNameField.getText();
                String userGender = (String)regUserGenderBox.getSelectedItem();
                String PNum = regUserPNumField.getText();
                String userEmail = regUserEmailField.getText();
                String userAddress = regUserAddressField.getText();
                int UserId = new SelectUsers().getUserID()+1;
                //将用户信息加载到数据库

                if(userType.equals("农户"))
                {
                    if(!PNum.matches("\\d{11,12}"))
                    {
                        JOptionPane.showMessageDialog(registrationErrorPanel, "注册失败，联系电话是11或12位数字组成!");
                    }
                    else
                    {
                        Users u1 = new Users(UserId,userType,username,password,userGender,PNum,userEmail,userAddress);
                        boolean a = new UserDao().insertUser(u1);
                        Farmer farmer = new Farmer(UserId,userReallyName,userGender,password,userAddress,PNum);
                        boolean b = new FarmerDao().insertFarmer(farmer);
                        JOptionPane.showMessageDialog(registrationFrame, "注册成功,请登录!");
                        registrationFrame.dispose(); // 关闭注册窗口
                    }
                }
                else
                {
                    if(!PNum.matches("\\d{11,12}"))
                    {
                        JOptionPane.showMessageDialog(registrationErrorPanel, "注册失败，联系电话是11或12位数字组成!");
                    }
                    else if(!userEmail.matches("\\w+@\\w+(\\.[a-z]{2,3}){1,2}"))
                    {
                        JOptionPane.showMessageDialog(registrationErrorPanel, "注册失败，请输入正确的电子邮箱格式（包含@符号）");
                    }
                    else
                    {
                        Users u2 = new Users(UserId,userType,username,password,userGender,PNum,userEmail,userAddress);
                        boolean c = new UserDao().insertUser(u2);
                        JOptionPane.showMessageDialog(registrationFrame, "注册成功,请登录!");
                        registrationFrame.dispose(); // 关闭注册窗口
                    }
                }

            }
        });

        if(userType.equals("农户"))
        {
            registrationPanel.add(userReallyNameLabel);
            registrationPanel.add(regUserReallyNameField);
            registrationPanel.add(userGenderLabel);
            registrationPanel.add(regUserGenderBox);
            registrationPanel.add(userPNumLabel);
            registrationPanel.add(regUserPNumField);
            registrationPanel.add(userAddressLabel);
            registrationPanel.add(regUserAddressField);
        }
        else
        {
            registrationPanel.add(userGenderLabel);
            registrationPanel.add(regUserGenderBox);
            registrationPanel.add(userPNumLabel);
            registrationPanel.add(regUserPNumField);
            registrationPanel.add(userEmailLabel);
            registrationPanel.add(regUserEmailField);
            registrationPanel.add(userAddressLabel);
            registrationPanel.add(regUserAddressField);
        }

        registrationPanel.add(new JLabel());
        registrationPanel.add(completeRegistrationButton);
        registrationPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        registrationFrame.add(registrationPanel);
        registrationFrame.setVisible(true);
    }

    //根据用户类型在此处添加身份验证逻辑
    private boolean authenticateUser(String username, String password, String userType) {
        List<Users> list = new SelectUsers().getUserData();
        for(Users u:list)
        {
            if(u.getUserName().equals(username) && u.getPassword().equals(password) && u.getUserType().equals(userType))
                return true;
        }
        return false;
    }

    // 根据用户类型打开相应用户界面
    private void openUserInterface(String userType,String userName) {
        switch (userType) {
            case "管理员":
                try {
                    new AdminInterface().init(userName);
                    this.dispose();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case "农户":
                try {
                    new FarmerInterface().init(userName);
                    this.dispose();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                }
                break;
            case "消费者":
                try {
                    new ConsumerInterface().init(userName);
                    this.dispose();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            default:
                break;
        }
    }

//    // 主方法
//    public static void main(String[] args) {
//        SwingUtilities.invokeLater(new Runnable() {
//            @Override
//            public void run() {
//                new FarmingSystemGUI();
//            }
//        });
//    }

}










